package com.ml.mall.service.file.impl;

import com.ml.mall.bean.base.ApiRestResult;
import com.ml.mall.bean.req.file.FileUploadDto;
import com.ml.mall.bean.req.file.ImageDto;
import com.ml.mall.enums.CommonEnum;
import com.ml.mall.exception.BizException;
import com.ml.mall.security.JwtUtil;
import com.ml.mall.service.file.FileService;
import com.ml.mall.utils.FileUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @program: mall-ml
 * @description: 文件操作实现
 * @author: Daizh
 * @create: 2021-06-16 17:13
 **/
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    // 处理公司logo及用户头像;目录；支持传多张；
    @Override
    public Map<String, List<String>> uploadFile(MultipartFile[] fileList, String rootName) {
        Map<String, List<String>> picUrlMap = new HashMap<>();
        // 用于存放图片路径
        List<String> picUrlList = new ArrayList<>();
        if(fileList.length == 1){
            String picurl = saveFile(fileList[0],rootName);
            picUrlList.add(picurl);
            picUrlMap.put("picUrl",picUrlList);
        }else {
            throw new BizException(CommonEnum.FILE_UPLOAD_TOOMANY);
        }
        return picUrlMap;
    }

    // 处理商品上传的图片
    @Override
    public Map<String, List<ImageDto>> uploadProdFile(MultipartFile[] fileList, FileUploadDto dto, String rootName)  {
        if(dto.getIndex()==null || dto.getIndex().size()==0){
            throw new BizException(CommonEnum.FILE_UPLOAD_INDEX_IS_NULL);
        }
        Map<String, List<ImageDto>> imageMap = new HashMap<>();
        List<ImageDto> imageList = new ArrayList<>();
        if(fileList.length > 0) {
            for (int i = 0; i < fileList.length; i++) {
                String picurl  = saveFile(fileList[i],rootName);
                ImageDto image = new ImageDto(picurl, dto.getIndex().get(i));
                imageList.add(image);
                imageMap.put("picUrl",imageList);
            }
        }else {
            throw new BizException(CommonEnum.FILE_UPLOAD_ERROR);
        }
        return imageMap;
    }

    //删除图片：注意调用场景：main可以实现删除；而test内无法删除
    @Override
    public void delPicByUrl(String picUrl)  {
        log.info("delPicByUrl===={}",picUrl);
        File fileDir = FileUploadUtils.getImgDirFile();
        File dirFile = new File(fileDir.getAbsolutePath(), picUrl);
        if(dirFile.exists()){
            Boolean isDelete = dirFile.delete();
            log.info("isDelete===={}",isDelete);
        }
    }


    // 进行上传操作
    private String saveFile(MultipartFile mf,String rootName) {
        log.info("rootName=={}",rootName);
        // 1.获取上传文件的名称
        String oldName = mf.getOriginalFilename();
        // 2.根据当前时间获取文件夹的名字
        String userPath = JwtUtil.getCurrentUser().getAcc();
        String childPathName = "/images/"+ userPath +"/" + rootName;
        // 3. 如果当前目录不存在，则创建一个。
        // 存放上传图片的文件夹
        File fileDir = FileUploadUtils.getImgDirFile();
        File dirFile = new File(fileDir.getAbsolutePath(), childPathName);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        File[] filesArr = dirFile.listFiles();
        if (filesArr.length > 500) {
            throw new BizException(CommonEnum.FILE_PIC_TOOMANY);
        }
        // 4.生成文件的新名称
        String newName = FileUploadUtils.getNewNameByUUID(oldName);
        // 5.上传文件
        File file = new File(dirFile, newName);
        try {
            mf.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 注意：上传文件到页面使用相对路径。不能使用绝对路径。
        return childPathName + "/" + newName;
    }

    public static void main(String[] args) throws IOException {
        FileServiceImpl fileService = new FileServiceImpl();
        fileService.delPicByUrl(  "/images/admin/logo/01DEE9266681457DB0254545E5E018F9.png");
    }

}
